<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的购物车 - eBusiness</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <script th:src="@{/js/jquery-3.6.0.min.js}"></script>
    <script th:src="@{/js/slider.js}"></script>
</head>
<body>
    <div th:replace="~{common/header :: header}"></div>

    <div class="slider-container">
        <div class="slides">
            <img th:src="@{/images/1.jpg}" alt="Slide 1" class="slide active">
            <img th:src="@{/images/2.png}" alt="Slide 2" class="slide">
            <img th:src="@{/images/3.png}" alt="Slide 3" class="slide">
        </div>
        <div class="navigation-arrows">
            <span class="prev-arrow">&#10094;</span>
            <span class="next-arrow">&#10095;</span>
        </div>
        <div class="pagination-dots">
            <span class="dot active" data-slide="0"></span>
            <span class="dot" data-slide="1"></span>
            <span class="dot" data-slide="2"></span>
        </div>
    </div>

    <div class="category-search-bar-container">
        <div class="main-nav">
            <ul>
                <li><a th:href="@{/index}">首页</a></li>
                <li th:each="type : ${goodsTypes}"><a th:href="@{/category(typeId=${type.id})}" th:text="${type.typename}"></a></li>
            </ul>
        </div>
        <div class="header-search">
            <form th:action="@{/search}" method="get">
                <input type="text" name="keyword" placeholder="请输入关键词" th:value="${keyword}">
                <button type="submit">搜索</button>
            </form>
        </div>
    </div>

    <div class="main-content">
        <h2>我的购物车</h2>
        <p th:if="${error}" style="color: red;" th:text="${error}"></p>
        <table class="cart-table">
            <thead>
                <tr>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>现价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="entry : ${cartDetails}">
                    <td><img th:src="@{/images/{picture}(picture=${entry.goods.gpicture})}" alt="商品图片" style="width: 50px; height: 50px;"></td>
                    <td th:text="${entry.goods.gname}"></td>
                    <td th:text="${entry.goods.grprice}"></td>
                    <td>
                        <form th:action="@{/updateCart}" method="post" class="update-cart-form" style="display: inline;">
                            <input type="hidden" name="cartItemId" th:value="${entry.get('cartItemId')}">
                            <div class="quantity-controls">
                                <button type="button" class="quantity-btn minus-btn">-</button>
                                <input type="number" name="quantity" th:value="${entry.get('shoppingNum')}" min="1" class="quantity-input">
                                <button type="button" class="quantity-btn plus-btn">+</button>
                            </div>
                        </form>
                    </td>
                    <td th:text="${entry.get('subtotal')}"></td>
                    <td>
                        <form th:action="@{/removeCartItem}" method="post" style="display: inline;">
                            <input type="hidden" name="cartItemId" th:value="${entry.get('cartItemId')}">
                            <button type="submit" class="remove-item-btn">删除</button>
                        </form>
                    </td>
                </tr>
                <tr th:if="${#lists.isEmpty(cartDetails)}">
                    <td colspan="6">购物车为空。</td>
                </tr>
            </tbody>
        </table>

        <div class="cart-summary">
            <p>购物金额总计(不含运费) ¥<span id="totalAmount" th:text="${totalAmount}"></span>元</p>
            <form th:action="@{/clearCart}" method="post" id="clearCartForm">
                <button type="submit" th:disabled="${#lists.isEmpty(cartDetails)}" id="clearCartBtn">清空购物车</button>
            </form>
            <form th:action="@{/checkout}" method="post">
                <button type="submit" th:disabled="${#lists.isEmpty(cartDetails)}" class="cart-checkout-btn">去结算</button>
            </form>
        </div>
    </div>

    <div th:replace="~{common/footer :: footer}"></div>

    <script>
        $(document).ready(function() {
            // Update quantity via AJAX (now listening to form submit)
            $('.cart-table .update-cart-form').on('submit', function(event) {
                event.preventDefault(); // Prevent default form submission (stops the redirect)

                const form = $(this);
                const quantityInput = form.find('.quantity-input');
                const cartItemId = form.find('input[name="cartItemId"]').val();
                const newQuantity = parseInt(quantityInput.val()); // Ensure integer
                const row = form.closest('tr');
                const price = parseFloat(row.find('td').eq(2).text()); // Assuming price is in the 3rd column

                if (isNaN(newQuantity) || newQuantity < 1) {
                    alert("数量必须是大于0的整数！");
                    quantityInput.val(1); // Reset to 1 or previous valid quantity
                    return;
                }

                if (newQuantity <= 0) {
                    if (!confirm("数量为0将从购物车中移除此商品，确定吗？")) {
                        quantityInput.val(1); // Revert to 1 if user cancels removal
                        return; 
                    }
                }

                $.ajax({
                    url: '/updateCart',
                    type: 'POST',
                    data: {
                        cartItemId: cartItemId,
                        quantity: newQuantity
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.message);
                            if (newQuantity <= 0) {
                                row.remove(); // Remove row if quantity is 0 or less
                            } else {
                                row.find('td').eq(4).text((price * newQuantity).toFixed(2)); // Update subtotal
                            }
                            $('#totalAmount').text(response.totalAmount.toFixed(2)); // Update total amount
                            
                            // Check if cart is empty after update/removal
                            if (response.totalAmount === 0) {
                                if ($('.cart-table tbody tr').not(':has(td[colspan])').length === 0) { // Check if no actual item rows left
                                    $('.cart-table tbody').empty().append('<tr><td colspan="6">购物车为空。</td></tr>');
                                }
                                $('#clearCartBtn').prop('disabled', true);
                                $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', true); // Disable checkout button
                            } else {
                                // If cart is not empty, ensure buttons are enabled
                                $('#clearCartBtn').prop('disabled', false);
                                $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', false);
                            }

                        } else {
                            alert(response.message);
                            // Reload page if update failed to revert to correct state
                            location.reload(); 
                        }
                    },
                    error: function(xhr) {
                        const response = JSON.parse(xhr.responseText);
                        alert(response.message || '更新购物车失败，请稍后再试！');
                        location.reload(); // Reload page on error
                    }
                });
            });

            // Handle plus/minus button clicks
            $('.quantity-btn').on('click', function() {
                const btn = $(this);
                const quantityInput = btn.siblings('.quantity-input');
                let currentQuantity = parseInt(quantityInput.val());

                if (isNaN(currentQuantity)) {
                    currentQuantity = 1; // Default if input is empty or invalid
                }

                if (btn.hasClass('plus-btn')) {
                    currentQuantity++;
                } else if (btn.hasClass('minus-btn')) {
                    currentQuantity--;
                }
                
                quantityInput.val(currentQuantity); // Update the input field

                // Trigger the form submit to update immediately
                quantityInput.closest('form').submit();
            });

            // Ensure '清空购物车' and '去结算' button states are correct on load and after updates
            function updateCartButtonsState() {
                const totalAmount = parseFloat($('#totalAmount').text());
                if (totalAmount === 0) {
                    $('#clearCartBtn').prop('disabled', true);
                    $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', true);
                } else {
                    $('#clearCartBtn').prop('disabled', false);
                    $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', false);
                }
            }
            updateCartButtonsState(); // Call on document ready

            // Remove item via AJAX (now listening to form submit)
            $('.cart-table form[th\\:action="@{/removeCartItem}"], .cart-table form[action="/removeCartItem"]').on('submit', function(event) {
                event.preventDefault(); // Prevent default form submission

                const form = $(this);
                const cartItemId = form.find('input[name="cartItemId"]').val();
                const row = form.closest('tr');

                if (!confirm("确定要从购物车中移除此商品吗？")) {
                    return;
                }

                $.ajax({
                    url: '/removeCartItem',
                    type: 'POST',
                    data: { cartItemId: cartItemId },
                    success: function(response) {
                        if (response.success) {
                            alert(response.message);
                            row.remove(); // Remove the row from the table
                            $('#totalAmount').text(response.totalAmount.toFixed(2)); // Update total amount

                            // Check if cart is empty after removal
                            if (response.totalAmount === 0) {
                                if ($('.cart-table tbody tr').not(':has(td[colspan])').length === 0) { // Check if no actual item rows left
                                    $('.cart-table tbody').empty().append('<tr><td colspan="6">购物车为空。</td></tr>');
                                }
                                $('#clearCartBtn').prop('disabled', true);
                                $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', true);
                            } else {
                                // If cart is not empty, ensure buttons are enabled
                                $('#clearCartBtn').prop('disabled', false);
                                $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', false);
                            }
                        } else {
                            alert(response.message);
                            location.reload(); // Reload page on error
                        }
                    },
                    error: function(xhr) {
                        const response = JSON.parse(xhr.responseText);
                        alert(response.message || '移除商品失败，请稍后再试！');
                        location.reload(); // Reload page on error
                    }
                });
            });

            // Clear cart via AJAX (assuming /clearCart endpoint exists or will be created)
            $('#clearCartForm').on('submit', function(event) {
                event.preventDefault(); // Prevent default form submission

                if (!confirm("确定要清空购物车吗？")) {
                    return;
                }

                $.ajax({
                    url: '/clearCart', // You might need to implement this backend endpoint
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            alert(response.message);
                            $('.cart-table tbody').empty().append('<tr><td colspan="6">购物车为空。</td></tr>'); // Clear table content
                            $('#totalAmount').text('0.00'); // Set total to 0
                            $('#clearCartBtn').prop('disabled', true);
                            $('form[th\\:action="@{/placeOrder}"] button[type="submit"]').prop('disabled', true); // Disable checkout button
                        } else {
                            alert(response.message || '清空购物车失败！');
                        }
                    },
                    error: function() {
                        alert('清空购物车失败，请稍后再试！');
                    }
                });
            });
        });
    </script>
</body>
</html> 